package sapling.web.admin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import sapling.dao.BatchDao;
import sapling.form.BatchForm;
import sapling.model.Batch;
import sapling.model.Tree;
import sapling.service.StorageService;
import sapling.service.TreeWellService;
import sapling.utils.FileUtil;

import java.util.Objects;

/**
 * Created by ever on 2016/10/9.
 */
@Controller
@RequestMapping(value = "/admin/batch")
public class BatchAction {

    @Autowired
    BatchDao batchDao;
    @Autowired
    TreeWellService treeWellService;
    @Autowired
    StorageService storageService;


    @RequestMapping("")
    public String list() {
        return "admin/batch/data";
    }

    @RequestMapping("/update")
    public String update(BatchForm from){
        if(Objects.nonNull(from.getBatch_id())){
            Subject currentUser = SecurityUtils.getSubject();
            String name = currentUser.getSession().getAttribute("username").toString();
            Batch batch=batchDao.findOne(from.getBatch_id());
            batch.setHeight(from.getHeight());
            batch.setChestbreadth(from.getChestBreadth());
            batch.setCrownwidth(from.getCrownWidth());
            batch.setSalenumber(from.getSalenumber());
            batchDao.save(batch);
            String srtid="";
            for (Tree value:batch.getTrees()) {
               // treeWellService.updateTree(value.getTree_id(),value.getTreeSpecies(),from.getChestBreadth(),from.getCrownWidth(),from.getHeight(),value.getClump(),name,from.getSalenumber(),from.getFile());
                srtid+=value.getTree_id()+";";
            }
            String imgurl= FileUtil.savefile(from.getFile());
            storageService.updateinfo(srtid,from.getChestBreadth(),from.getChestBreadthmax(),from.getCrownWidth(),from.getCrownWidthmax(),
                    from.getHeight(),from.getHeightmax(),from.getSalenumber(),from.getSalenumbermax(),from.getRemark(),imgurl,name,from.getCost());
        }
        return "redirect:/admin/finance/batch";
    }



    @RequestMapping("/setting")
    public String setting(BatchForm from){
        if(Objects.nonNull(from.getBatch_id())){
            Batch batch =batchDao.findOne(from.getBatch_id());
            batch.setDeathrate(from.getDeathrate());
            batchDao.save(batch);
        }
        return "redirect:/admin/finance/setting";
    }
}
